package com.yegs.jindie.quartz;

import com.yegs.jindie.JindieApplication;
import com.yegs.jindie.entity.BasisTO;
import com.yegs.jindie.entity.JobVo;
import com.yegs.jindie.entity.LoggerVo;
import com.yegs.jindie.repository.LoggerRepository;
import com.yegs.jindie.serviceImpl.JobServiceImpl;
import com.yegs.jindie.serviceImpl.LogServiceImpl;
import com.yegs.jindie.util.FTPTools;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class BaseJob implements Job{

    private BasisTO basisTO = (BasisTO) JindieApplication.applicationContext.getBean("basisTO");
    private LogServiceImpl logService = (LogServiceImpl) JindieApplication.applicationContext.getBean("logServiceImpl");
    private JobServiceImpl jobService = (JobServiceImpl) JindieApplication.applicationContext.getBean("jobServiceImpl");
    private static final SimpleDateFormat sdf_name = new SimpleDateFormat("yyyyMMdd");
    private static final SimpleDateFormat sdf_filter = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logService.saveBeginLog(this.getClass().getName(),"开始执行调度任务");
        JobVo jobVo = jobService.getJobByClassName(this.getClass().getName());
        Date beginDate = jobVo.getDate();
        Date endDate = new Date();
        try {
            beginDate = sdf_filter.parse("2020-12-29");
            endDate = sdf_filter.parse("2020-12-29");
        } catch (ParseException e) {
            e.printStackTrace();
            return;
        }
        Integer int_last = jobVo.getLast();
        if(sdf_name.format(beginDate).equals(sdf_name.format(endDate))){
            int_last ++ ;
        }else{
            int_last = 0;
        }
        //int_last = 1;
        String handle = handle(beginDate, endDate,int_last);
        jobVo.setLast(++int_last);
        jobVo.setDate(endDate);
        jobService.save(jobVo);
        logService.saveEndLog(this.getClass().getName(),handle);
    }
    protected abstract String handle(Date beginDate, Date endDate,Integer int_last);

    protected void upload(FileInputStream fi, String path){
        logService.saveBeginLog(this.getClass().getName(),"开始执行调度任务");
        boolean upload = FTPTools.upload(basisTO.getHostname(), basisTO.getPort(), basisTO.getUsername(), basisTO.getPassword(), basisTO.getWorkingPath(), fi, path);
        if(upload){
            logService.saveBeginLog(FTPTools.class.getName(),"上传成功");
        }else{
            logService.saveEndLog(FTPTools.class.getName(),"上传失败");
        }
    }
}
